<?php

namespace support\Service;

use support\Backend\BackendService;
use support\Container;
use support\Exception\ApiException;
use support\Model\ConfigDataModel;
use support\Model\ConfigModel;

class ConfigService extends BackendService
{

    private $configDataModel;

    public function __construct()
    {
        $this->model = Container::get(ConfigModel::class);
        $this->configDataModel = Container::get(ConfigDataModel::class);
    }

    public function getAllList(array $where, array $field = ['*'], array $order = [], array $with = [])
    {
        $list = $this->model->getAllList($where, $field, $order, $with);
        return $list;
    }

    public function getUserCountByWhere($where)
    {

        return $this->model->getCountByWhere($where);
    }

    public function getConfigData($code)
    {
        $config = $this->model->where('code', $code)->first();
        if (!$config) return [];
        return $this->configDataModel->where('config_id', $config->id)
            ->select(['code', 'value', 'title', 'options', 'type'])
            ->where('status', 1)
            ->where('mark', 1)
            ->orderBy('sort')
            ->get()->toArray();
    }

    public function editConfigData($code, $params)
    {
        $config = $this->model->where('code', $code)->first();
        if (!$config) throw new ApiException('数据不存在');
        foreach ($params as $key => $item) {
            if (is_array($item)) {
                $item = implode(',', $item);
            }
            $info = $this->configDataModel->getInfoByWhere(['config_id' => $config->id, 'code' => $key]);
            if (!$info) continue;
            $this->configDataModel->updateById(['value' => $item], $info['id']);
        }
        return true;
    }
}